const addressUrl = 'https://restapi.amap.com/v3/geocode/regeo'
const app = getApp()
/**
  * 获取经纬度
  */
function getLocation(that) {
    return new Promise((resolve, reject) => {
        app.toPromise(wx.getStorage, {
            key: "location"
        }).then(res => {
            //经纬度已存在
            return Promise.resolve({
                longitude: res.data.lng,
                latitude: res.data.lat,
            })
        }).catch(err => {
            return app.toPromise(wx.getLocation, {
                type: 'gcj02'
            })
        }).then(res => {
            const location = {
                lng: res.longitude,
                lat: res.latitude,
            }
            wx.setStorage({
                key: 'location',
                data: location,
            })
            that.setData({
                location
            })
            resolve()
        }).catch(err => {
            that.setData({ //没有授权
                addressStatus: 1
            })
            reject()
        })
    })
}


/**
 * 点击按钮打开设置授权
 */
function handGetLocation(that) {
    return new Promise((resolve, reject) => {
        app.toPromise(wx.getSetting).then(res => {
            if (res.authSetting['scope.userLocation']) { //已经授权
                that.setData({
                    addressStatus: 2
                })
                resolve(getLocation(that))
            } else { //没有授权
                that.setData({
                    addressStatus: 1
                })
            }
        }).catch(err => {
            that.setData({
                addressStatus: 1
            })
            reject()
        })
    })

}

/**
 * 获取地址
 */
function loadAddress(that) {
    return app.toPromise(wx.request, {
        url: addressUrl,
        data: {
            key: app.gdConfig.key,
            location: [that.data.location.lng, that.data.location.lat].join(","),
            poitype: '商务住宅',
            extensions: 'all'
        }
    }).then(res => {
        let data = res.data.regeocode
        try {
            that.setData({
                address: data.formatted_address,
                dtCode: data.addressComponent.adcode,
                ctCode: data.addressComponent.adcode.slice(0, 4) + '00',
                pcCode: data.addressComponent.adcode.slice(0, 3) + '000'
            })
        } catch (err) {
            that.setData({
                address: data.addressComponent.province + data.addressComponent.city + data.addressComponent.district + data.addressComponent.street
            })
        }
        wx.setStorage({
            key: 'address',
            data: that.data.address,
        })
    })
}
module.exports = {
    getLocation,
    handGetLocation,
    loadAddress
}